import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

class ComPrintingText extends StatefulWidget {
  final String text;
  final Color textColor;
  final double textSize;
  final Duration delay; // 延迟执行
  final int maxLines; // 文字最大行数

  const ComPrintingText({
    super.key,
    required this.text,
    required this.textColor,
    required this.textSize,
    this.maxLines = 2,
    this.delay = const Duration(seconds: 0),
  });

  @override
  State<ComPrintingText> createState() => _ComPrintingTextState();
}

class _ComPrintingTextState extends State<ComPrintingText>
    with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  late Tween<double> stringTween;
  late Animation<double> stringAnimation;
  late CurveTween curveTween;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      vsync: this,
      duration: Duration(seconds: 1),
    );
    curveTween = CurveTween(curve: Curves.easeInOut);
    stringTween = Tween(begin: 0, end: widget.text.length.toDouble());
    stringAnimation = stringTween.animate(_controller.drive(curveTween));
    Future.delayed(widget.delay, () {
      _controller.forward();
    });
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
      animation: stringAnimation,
      builder: (ctx, child) {
        return Text(
          stringAnimation.value.toInt() == 0
              ? ''
              : widget.text.substring(0, stringAnimation.value.toInt()),
          maxLines: widget.maxLines,
          overflow: TextOverflow.ellipsis,
          style: TextStyle(fontSize: widget.textSize, color: widget.textColor),
        );
      },
    );
  }
}
